<template>
<div class="container">
  <h1>登录</h1>
  <div class="from-panel">
    <el-form :labelPosition="labelPosition" ref="signInForm" :rules="rules" :model="user">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input type="password" v-model="user.pwd"></el-input>
      </el-form-item>

      <div class="oprator">
        <el-button class="submit" type="primary" @click="submitForm('signInForm')">提交</el-button>
      </div>
    </el-form>
  </div>
</div>
</template>

<style lang="css" scoped>
  .container {
    padding: 50px 10%;
    background: #fafafa;
    min-height: calc(100vh - 180px);
  }

  h1 {
    text-align: center;
    font-weight: 100;
    font-size: 40px;
    margin-bottom: 35px;
    margin-top: 0;
  }

  .from-panel {
    width: 30%;
    margin: 0 auto;
  }

  .oprator {
    margin-top: 30px;
    text-align: center;
  }
</style>

<script>
    export default {
      name: 'signIn',
      data: function () {
        return {
          labelPosition: 'top',
          user: {
            name: '',
            pwd: '',
          },
          rules: {
            name: [
              {required: true, message: '请输入用户名', trigger: 'blur'},
              {min: 2, max: 7, message: '长度在2-7个字符之间', trigger: 'blur'}
            ],
            pwd: [
              {required: true, message: '必须填写', trigger: 'blur'},
            ],
          }
        };
      },
      methods: {
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.$api.SDK.User.logIn(this.user.name, this.user.pwd).then((loginUser) => {
                this.$store.dispatch('login', loginUser.toFullJSON());
                localStorage.setItem('loginUser', JSON.stringify(loginUser.toFullJSON()));
                this.$router.push({path: '/'});
                this.$message.success('登录成功!');
              }).catch((error) => {
                console.log(error);
                this.$message.error(error.message);
              })
            }
            else {
              console.log('submit error!');
              this.$message.error('填写信息有误，请按提示填写!');
              return false;
            }
          })
        }
      }
    }
</script>
